import { Injectable, NestInterceptor, ExecutionContext, CallHandler, HttpException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import config from 'src/config';
import AesUtils from 'src/utils/aes';
import { LoggerService } from 'src/common/modules/logger/logger.service';
import { IHttpLog } from 'src/common/modules/logger/logger.types';
import { randomString } from 'src/utils';
import * as moment from 'moment';
import { IRequest } from 'src/interface/common';

@Injectable()
export class AppRequestInterceptor implements NestInterceptor {
	constructor(
		private readonly loggerService: LoggerService,
	){}
	intercept(context: any, next: CallHandler): Observable<any> {

		let req = context.switchToHttp().getRequest() as IRequest;

		if(req.path.startsWith("/app")){
			req.trackId=randomString(32)
			req.requestTime = Date.now();
			let nodeEnv=process.env.NODE_ENV||"local"
			let isServer=nodeEnv=="docker"
			// if(config.env=="dev"||config.env=="pre"||config.env=="test"||(!isServer&&config.env=="prod")){
			// 	if(req.headers["api-secret"]=="1"){
			// 		if(req.body.data){
			// 			req.body=AesUtils.decryptToJson(req.body.data)
			// 		}
			// 	}
			// }else{
			// 	if(req.body.data){
			// 		req.body=AesUtils.decryptToJson(req.body.data)
			// 	}
			// }
			
			return next
			.handle()
			.pipe(
				tap(async (data) => {
					let d=await data
					const response = context.switchToHttp().getResponse()
					let logParams:IHttpLog={
						trackId:req.trackId,
						ip:req.headers["x-real-ip"] as string||req.headers["x-forwarded-for"] as string||"",
						user: req.user?._id||"",
						url: req.url,
						method: req.method,
						timeMs: Date.now()-req.requestTime,
						headers: req.headers,
						params: req.params,
						body: req.body,
						responseFrom:"db",
						responseCode:response.statusCode,
						responseData:d
					}
					this.loggerService.writeHttpLog(logParams)
				}),
			);
		}
		return next.handle()
	}
}
